import React, { Component } from 'react';
import { Dialog,Input, Button, Select ,Lable ,Form, Field, Feedback} from '@icedesign/base';
import IceContainer from '@icedesign/container';
import { enquireScreen } from 'enquire-js';
import axios from 'axios';
import {hashHistory} from 'react-router';
import RoleList from '../RoleList';
import {GET,POST,PUT} from '../../../../utils/public'
import './AddRolesDialog.scss';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';

const FormItem = Form.Item;
const defaultValue = {
  keywords: '',
  type: 'post',
  content: '',
};

export default class AddRolesDialog extends Component {
  static displayName = 'AddRolesDialog';

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      visible: false,
      value: defaultValue,
      isMobile: false,
      type:null,  //窗口打开方式，add or edit
      id:null,  //触发打开窗口的节点的 id
      dataId:null,  //触发打开窗口的节点的 dataId
      name:'',//角色名
      comment:'',//角色备注
      style:{
        
      },
      id:[],
    }
    this.handleChildChange=this.handleChildChange.bind(this); //监听子组件变化
    this.addToSave = this.addToSave.bind(this);
    this.editToSave = this.editToSave.bind(this);
    
  }

  handleChildChange(newState){ //处理子函数传回来的state,改变自身的state
    if(newState){
        this.setState(newState);  
        //console.log(this.state.id)  
    }
  }

  componentDidMount() {
    this.enquireScreenRegister();
    //
  
  }

  enquireScreenRegister = () => {
    const mediaCondition = 'only screen and (max-width: 720px)';

    enquireScreen((mobile) => {
      this.setState({
        isMobile: mobile,
      });
    }, mediaCondition);
  }

  showDialog =()=> {
    this.field.reset()
    this.setState({ visible: true });
  }

  hideDialog=()=> {
    this.field.reset()
    this.setState({visible: false });
  }

  onOpen =(codeID,type)=>{
    //codeID数据格式：id+","+data.id
    let id = codeID.split(',')[0];
    let dataId = codeID.split(',')[1];
    //当前节点的code,及窗口打开类型：添加 add 编辑 edit
    this.setState({type,id,dataId})
    this.field.setValues({name:'',comment:'',precondition:'',symbol:''})
    if(type == 'edit'){
      //编辑角色权限时
      let url = 'api/permissions/'+dataId;
      GET(url)
        .then(res=>{
          if(!res){
            Feedback.toast.error('与服务器失去连接，稍后再试！')
            return;
          }else if(res.code == 200 && res.success){
            this.field.setValues({name:res.data.name,symbol:res.data.symbol,precondition:res.data.precondition})
          }else if(res.code==401 && res.msg=='请登录!'){
            Feedback.toast.error('等过过期，请重新登录！')
            setTimeout(()=>{
              hashHistory.push('/login');
            },3000) 
          }else{
            Feedback.toast.error(`网络错误，${res.msg}`)
            return;
          }
        },error=>{
          Feedback.toast.error(`网络错误，${error}`)
          return;
        }).catch(errors=>{
          Feedback.toast.error(`出错了，${errors}`)
          return;
        })
    }
    setTimeout(()=>{
      this.setState({ visible: true });
    },1000)
    
  }

  onClose = () => {
    this.setState({name:'',comment:''})
    this.setState({
      visible: false
    })
  }
  handleSubmit=()=> {
      //校验
      this.field.validate((errors, values) => {
        if(errors){
          console.log(errors, values);
          return ;
        }
      });
    (this.state.type ==='edit')? this.editToSave():this.addToSave();
  }

  //添加角色保存
  addToSave=()=>{
    let url = 'api/permissions';
    let name = this.field.getValues().name;
    let comment = this.field.getValues().comment;
    this.field.setValues({parentCode:this.state.id})
    let data = this.field.getValues();
  
    POST(url,data)
      .then(res=>{
        if(!res){
          Feedback.toast.error('与服务器失去连接，稍后再试！')
          return;
        }else if(res.code == 200 && res.success){
          Feedback.toast.success('保存成功!')
          this.hideDialog();
          this.props.onGetTree(true) 
        }else if(res.code==401 && res.msg=='请登录!'){
          Feedback.toast.error('登录过期，请重新登录！')
          setTimeout(()=>{
            hashHistory.push('/login');
          },3000) 
        }else{
          Feedback.toast.error(`保存失败，${res.msg}`)
          return;
        }
      },error=>{
        Feedback.toast.error(`保存失败，${error}`)
        return;
      }).catch(errors=>{
        Feedback.toast.error(`出错了，${errors}`)
        return;
      })
  }

  //编辑角色保存
  editToSave=()=>{
    let url ='api/permissions/'+this.state.dataId;
    //编辑时，若不改变name和comment值时，无法从field.getValues中获取
    this.field.validate((errors, values) => {
      if(errors){
        console.log(errors, values);
        return ;
      }
      PUT(url,values)
        .then(res=>{
            if(!res){
              Feedback.toast.error('与服务器失去连接，稍后再试！')
              return;
            }else if(res.code == 200 && res.success){
              Feedback.toast.success('保存成功!')
              this.hideDialog();
              this.props.onGetTree(true) 
            }else if(res.code==401 && res.msg=='请登录!'){
              Feedback.toast.error('登录过期，请重新登录！')
              setTimeout(()=>{
                hashHistory.push('/login');
              },3000) 
            }else{
              Feedback.toast.error(`保存失败，${res.msg}`)
              return;
            }
          },error=>{
            Feedback.toast.error(`保存失败，${error}`)
            return;
          }).catch(errors=>{
            Feedback.toast.error(`出错了，${errors}`)
            return;
          })
    });
  
  }

  resolveError=errors=>{
    //异常处理
    errors.forEach((item)=>{
      const { getError, setError, setErrors } = this.field;
      let name = item.field;
      let msg = item.message;
      setError(name, msg);
    })
  }

  onCancel = () => {
    this.setState({
      visible: false
    })
  }

  onFormChange = (value) => {
    this.setState({
      value,
    });
  };

  render() {
    const { isMobile } = this.state;
    
    const addRolesDialog = {
      ...styles.addRolesDialog,
    };
    const formItemLayout = {
            labelCol: {
              fixedSpan: 10
            },
            wrapperCol: {
              span: 14
            }
          }
    const init = this.field.init;
  
    // 响应式处理
    if (isMobile) {
      addRolesDialog.width = '300px';
    }

    return (
      <IceContainer>
        <Dialog
          className="simple-form-dialog"
          style={addRolesDialog}
          autoFocus={false}
          hasMask={false}
          title="角色管理"
          {...this.props}
          onOk={this.handleSubmit}
          onCancel={this.hideDialog}
          onClose={this.hideDialog}
          visible={this.state.visible}
      
        >
        <Form direction="ver" field={this.field}>
            {/* <FormItem label=" " {...formItemLayout}>
              <Button type="primary" onClick={this.handleSubmit.bind(this)}>保存</Button>&emsp;
              <Button  onClick={this.onCancel}>取消</Button>
            </FormItem> */}

            <FormItem label="角色名" {...formItemLayout} >
              <Input placeholder="" required {...init("name",{ rules: [{ required: true,message: "不能为空" }]})}/>
            </FormItem>

            <FormItem label="权限标识" {...formItemLayout} >
              <Input placeholder="" required {...init("symbol",{ rules: [{ required: true,message: "不能为空" }]})}/>
            </FormItem >

            <FormItem label="权限前置条件" {...formItemLayout} >
              <Input placeholder="" required {...init("precondition")}/>
            </FormItem >

            <FormItem label="备注说明"  {...formItemLayout}>
              <Input multiple placeholder="" {...init("comment")} />
            </FormItem>
            
            {/* <RoleList id={this.state.id} dataId={this.state.dataId} type={this.state.type}  onChange={this.handleChildChange} /> */}
        </Form>
        </Dialog>
      
      </IceContainer>
    );
  }
}

const styles = {
  addRolesDialog: { width: '640px'},
  input: { width: '100%' },

};
